package com.loopj.android.image;

import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.InputStream;

/**
 * author zhaoxudong
 * Version 1.0
 * ModifiedBy
 * date 2021-02-26 14:05
 * description 获取联系人头像资源
 */
public class ContactImage implements SmartImage {
    private long contactId;

    /**
     * 构造函数
     *
     * @param contactId 联系人id
     */
    public ContactImage(long contactId) {
        this.contactId = contactId;
    }

    /**
     * 获取位图资源
     *
     * @param context context
     * @return PixelMap
     */
    public PixelMap getBitmap(Context context) {
        PixelMap bitmap = getPixelMap(contactId, context);

        return bitmap;
    }

    private PixelMap getPixelMap(long resId, Context context) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource((int) resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}